package com.frxuexi.park2305.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.room.UserEntity
import com.frxuexi.park2305.R
import com.frxuexi.park2305.databinding.ActivityRegisterBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/app/RegisterActivity")
@AndroidEntryPoint
class RegisterActivity : BaseActivity<ActivityRegisterBinding,UserIntent,UserViewModel>() {
    override val binding: ActivityRegisterBinding by lazy { ActivityRegisterBinding.inflate(layoutInflater) }
    override val vm: UserViewModel by viewModels<UserViewModel>()
    var code=""

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        ToastUtils.showLong("注册成功"+it.data)
                        finish()
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {

        binding.registerSendcode.setOnClickListener {
            val uname = binding.registerUname.text.toString()
            if(uname.isEmpty()){
                ToastUtils.showLong("手机号不能为空")
                return@setOnClickListener
            }
            if(!uname.matches(Regex("1[0-9]{10}"))){
                ToastUtils.showLong("不是合法账号")
                return@setOnClickListener
            }
            code= (1000..9999).random().toString()
            ToastUtils.showLong(code)
        }

        binding.btnRegister.setOnClickListener {
            val uname = binding.registerUname.text.toString()
            val pass = binding.registerPass.text.toString()
            val pass2 = binding.registerPass2.text.toString()
            val code = binding.registerCode.text.toString()
            if(pass!=pass2){
                ToastUtils.showLong("两次密码不一致")
                return@setOnClickListener
            }
            if(this.code!=code){
                ToastUtils.showLong("验证码不正确")
                return@setOnClickListener
            }
            val userEntity = UserEntity(null, uname, pass)
            vm.sendIntent(UserIntent.register(userEntity))
        }
    }

}